package com.xueshan.disruptor.common.config;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.xueshan.disruptor.common.event.HelloEventFactory;
import com.xueshan.disruptor.common.event.HelloEventHandler;
import com.xueshan.disruptor.common.event.MessageModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * created with IDEA
 *
 * @author:huqm
 * @date:2021/2/1
 * @time:20:34 <p>
 *
 * </p>
 */
@Configuration
public class MqConfig {
    @Bean("messageModel")
    public RingBuffer<MessageModel> messageRingBuffer(){
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Disruptor disruptor = new Disruptor<>(new HelloEventFactory(), 1024*1024, executorService, ProducerType.SINGLE, new YieldingWaitStrategy());
        initDisruptor(disruptor);
        disruptor.start();
        return disruptor.getRingBuffer();
    }

    private void initDisruptor(Disruptor disruptor){
        HelloEventHandler[] consumer = new HelloEventHandler[1];
        for(int i=0;i<consumer.length;i++){
            consumer[i]= new HelloEventHandler();
        }
        disruptor.handleEventsWith(consumer);
    }


}
